package com.niiwoo.civet.trade.service.dubbo.invest;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.dto.common.sendmessage.InvestReceiveDTO;
import com.niiwoo.civet.account.service.MessageSendDubboService;
import com.niiwoo.civet.trade.dao.entity.InvestorReceiveRecord;
import com.niiwoo.civet.trade.service.invest.InvestorReceiveNoticeJobDubboService;
import com.niiwoo.civet.trade.service.local.refund.InvestorReceiveNoticeService;

/**
 * 回款-投资人信息推送 
 *
 * @author: kevin.jia
 * @version 1.0.0
 */
@Service(version = "1.0.0")
public class InvestorReceiveNoticeJobDubboServiceImpl implements InvestorReceiveNoticeJobDubboService {

    @Reference(version = "1.0.0")
    private MessageSendDubboService messageSendDubboService;

    @Autowired
    private InvestorReceiveNoticeService investorReceiveNoticeService;

    private static final Logger log = LoggerFactory.getLogger(InvestJobDubboServiceImpl.class);

    @Override
    public void investorReceiveSendSmsAndLetter() {
        List<InvestReceiveDTO> noticeDTOList = investorReceiveNoticeService.selectYesterdayInvestorReceiveNotice();
        log.info("查询昨天回款记录###noticeDTOList={}", JSON.toJSONString(noticeDTOList));
        noticeDTOList.forEach( investReceiveDTO -> {
            try {
                log.info("投资回款通知###投资收支##发送短信请求###advanceDTO={}",JSON.toJSONString(investReceiveDTO));
                if(investReceiveDTO.getReceiveAmount().compareTo(BigDecimal.ZERO) > 0){
                    CompletableFuture.runAsync(() -> messageSendDubboService.sendSmsForInvestReceive(investReceiveDTO));
                    CompletableFuture.runAsync(() -> messageSendDubboService.sendLetterForInvestReceive(investReceiveDTO));
                }
            } catch (Exception e) {
                log.error("投资回款通知###投资收支变化###发送短信失败: userId={}, errorMessage={}", investReceiveDTO.getUserId(),e.getMessage());
            }
            //更新发送时间
            InvestorReceiveRecord receiveRecord = new InvestorReceiveRecord();
            receiveRecord.setId(investReceiveDTO.getId());
            receiveRecord.setLetterSendTime(new Date());
            receiveRecord.setSmsSendTime(new Date());
            investorReceiveNoticeService.updateInvestorReceiveRecord(receiveRecord);
        });
        //发送成功,删除2天前的投资人回记录
        investorReceiveNoticeService.deleteByReceivedDate(new DateTime().minusDays(2).toDate());
    }

}
